package com.ricchieri.common;

import java.io.File;
import java.util.List;

import org.apache.tools.ant.Project;
import org.apache.tools.ant.ProjectHelper;

import com.ricchieri.bean.AntAttributeTargetBean;
import com.ricchieri.bean.AntProcessBean;
import com.ricchieri.exception.AntException;

public class AntProcess {

	private void addAttibutes(List<AntAttributeTargetBean> attributes, Project project) {
		if(attributes != null) {
			for (AntAttributeTargetBean AntAttributeTargetBean : attributes) {
				project.setProperty(AntAttributeTargetBean.getField(), AntAttributeTargetBean.getValue());
			}
		}
	}

	private boolean checkTarget(String target, Project project) {

		boolean existe = false;

		for (Object key : project.getTargets().keySet()) {
			if (key.toString().equals(target)) {
				existe = true;
			}
		}
		return existe;
	}

	public void executeProcess(AntProcessBean process)throws AntException {

		File buildFile = new File(process.getFile());

		if (!buildFile.exists()) {
			throw new AntException("File: ".concat(process.getFile()).concat(" doesn't exist"));
		}

		Project project = new Project();
		project.setUserProperty("ant.file", buildFile.getAbsolutePath());
		project.init();

		ProjectHelper helper = ProjectHelper.getProjectHelper();
		project.addReference("ant.projectHelper", helper);

		helper.parse(project, buildFile);

		if (!checkTarget(process.getTarget(), project)) {
			throw new AntException("The target: ".concat(process.getTarget()).concat(" doesn't exist"));
		}

		addAttibutes(process.getAttributes(), project);

		try {
			project.executeTarget(process.getTarget());
		} catch (Exception e) {
			throw new AntException(e);
		}

	}
}